"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.WebLayout = void 0;

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _modal = _interopRequireDefault(require("./modal"));

var _position = require("./position");

var _configContext = require("../../../../extends/configContext");

var _usePopoverAnimation3 = require("../../../../utils/hooks/use-popover-animation.ts");

var _excluded = ["placement", "trigger", "followTrigger", "content", "children", "background", "zIndex", "triggerStyle", "triggerClassName", "modalStyle", "modalClassName", "innerStyle", "innerClassName", "triangleStyle", "triangleClassName", "triangleAtCenter", "showTriangle", "needOutsideClose", "closeCallback", "callback", "modalRefCallback", "onTriggerClick"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var WebLayout = function WebLayout(_ref) {
  var placement = _ref.placement,
      trigger = _ref.trigger,
      followTrigger = _ref.followTrigger,
      content = _ref.content,
      children = _ref.children,
      background = _ref.background,
      zIndex = _ref.zIndex,
      triggerStyle = _ref.triggerStyle,
      _ref$triggerClassName = _ref.triggerClassName,
      triggerClassName = _ref$triggerClassName === void 0 ? '' : _ref$triggerClassName,
      modalStyle = _ref.modalStyle,
      _ref$modalClassName = _ref.modalClassName,
      modalClassName = _ref$modalClassName === void 0 ? '' : _ref$modalClassName,
      innerStyle = _ref.innerStyle,
      _ref$innerClassName = _ref.innerClassName,
      innerClassName = _ref$innerClassName === void 0 ? '' : _ref$innerClassName,
      triangleStyle = _ref.triangleStyle,
      triangleClassName = _ref.triangleClassName,
      triangleAtCenter = _ref.triangleAtCenter,
      showTriangle = _ref.showTriangle,
      needOutsideClose = _ref.needOutsideClose,
      closeCallback = _ref.closeCallback,
      callback = _ref.callback,
      modalRefCallback = _ref.modalRefCallback,
      _ref$onTriggerClick = _ref.onTriggerClick,
      onTriggerClick = _ref$onTriggerClick === void 0 ? function () {} : _ref$onTriggerClick,
      props = _objectWithoutProperties(_ref, _excluded);

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix;

  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      visible = _useState2[0],
      setVisible = _useState2[1];

  var _useState3 = (0, _react.useState)({}),
      _useState4 = _slicedToArray(_useState3, 2),
      positionStyle = _useState4[0],
      setPositionStyle = _useState4[1]; // 浮层内容位置


  var _useState5 = (0, _react.useState)({}),
      _useState6 = _slicedToArray(_useState5, 2),
      trianglePositionStyle = _useState6[0],
      setTrianglePositionStyle = _useState6[1]; // 浮层三角位置


  var _useState7 = (0, _react.useState)(0),
      _useState8 = _slicedToArray(_useState7, 2),
      forceRefresh = _useState8[0],
      setForceRefresh = _useState8[1]; // 强制刷新


  var _usePopoverAnimation = (0, _usePopoverAnimation3.usePopoverAnimation)(setVisible, 150),
      _usePopoverAnimation2 = _slicedToArray(_usePopoverAnimation, 3),
      state = _usePopoverAnimation2[0],
      setState = _usePopoverAnimation2[1],
      unMount = _usePopoverAnimation2[2]; // 加载动画


  var triggerRef = (0, _react.useRef)(null); // 触发器引用

  var modalRef = (0, _react.useRef)(null); // 模态框引用
  //trigger dom

  var triggerDom = (0, _react.useMemo)(function () {
    return /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)("".concat(clsPrefix, "-popover__trigger"), triggerClassName),
      style: _objectSpread({
        display: "inline-block"
      }, triggerStyle),
      ref: triggerRef,
      onClick: function onClick() {
        onTriggerClick();
        trigger === "click" && setState(!visible);
      }
    }, children);
  }, [children, triggerStyle, triggerClassName, visible]); // modal dom

  var modalDom = (0, _react.useMemo)(function () {
    return /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)("".concat(clsPrefix, "-popover__content"), modalClassName),
      style: _objectSpread(_objectSpread(_objectSpread({}, modalStyle), positionStyle), {}, {
        padding: _position.fixPadding,
        zIndex: zIndex
      }),
      ref: modalRef
    }, /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)("".concat(clsPrefix, "-popover__inner"), innerClassName),
      style: _objectSpread(_objectSpread({}, innerStyle), {}, {
        background: background
      })
    }, content));
  }, [positionStyle, modalStyle, modalClassName, innerStyle, innerClassName, content]); // triangle dom

  var triangleDom = (0, _react.useMemo)(function () {
    return showTriangle ? /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)("".concat(clsPrefix, "-popover__arrow"), triangleClassName),
      style: _objectSpread(_objectSpread({
        background: background,
        zIndex: zIndex
      }, triangleStyle), trianglePositionStyle)
    }) : null;
  }, [trianglePositionStyle, triangleStyle, triangleClassName, showTriangle]); // 计算浮层弹框和三角的定位位置

  (0, _react.useEffect)(function () {
    //出现时才有modal
    if (triggerRef.current && modalRef.current) {
      var scroll = document.documentElement.scrollTop + document.body.scrollTop; //移动端可能取不到

      var modalRect = modalRef.current.getBoundingClientRect();
      var triggerRect = triggerRef.current.getBoundingClientRect(); // 获取不会被遮挡的位置

      var _placement = (0, _position.getVisiblePlacement)(placement, modalRect, triggerRect); // get popover position


      var res = followTrigger ? (0, _position.switchFollowPosition)(_placement, modalRect, triggerRect) : (0, _position.switchPosition)(_placement, modalRect, triggerRect, scroll);
      setPositionStyle(res);
      if (!showTriangle) return; //get triangle position

      var res2 = followTrigger ? (0, _position.switchFollowTrianglePosition)(_placement, triangleAtCenter, triggerRect) : (0, _position.switchTrianglePosition)(_placement, triangleAtCenter, triggerRect, scroll);
      setTrianglePositionStyle(res2);
    }
  }, [followTrigger, placement, triangleAtCenter, modalRef, visible, forceRefresh]); // 监听页面尺寸变化强制刷新

  (0, _react.useEffect)(function () {
    var handler = function handler() {
      setForceRefresh(function (prev) {
        return prev + 1;
      });
    };

    window.addEventListener("resize", handler);
    return function () {
      window.removeEventListener("resize", handler);
    };
  }, [setForceRefresh]); // 回调强制刷新

  (0, _react.useEffect)(function () {
    if (!callback) return;
    callback(function () {
      modalRef.current && setForceRefresh(function (v) {
        return v + 1;
      });
    });
  }, [callback]); // 回调弹框

  (0, _react.useEffect)(function () {
    modalRefCallback && modalRefCallback(modalRef);
  }, [modalRefCallback]); // 监听页面点击，允许外部关闭浮层

  (0, _react.useEffect)(function () {
    var listener;

    if (needOutsideClose && trigger === "click") {
      listener = function listener(event) {
        if (!modalRef.current || modalRef.current.contains(event.target)) {
          return;
        }

        setState(false);
      };

      window.addEventListener("click", listener);
    }

    return function () {
      window.removeEventListener("click", listener);
    };
  }, [needOutsideClose, trigger, setState]);
  return /*#__PURE__*/_react.default.createElement(_modal.default, _extends({
    visible: visible,
    triggerNode: triggerDom,
    clsPrefix: clsPrefix,
    closeCallback: closeCallback,
    state: state,
    setState: setState,
    unMount: unMount,
    trigger: trigger,
    followTrigger: followTrigger
  }, props), modalDom, triangleDom);
};

exports.WebLayout = WebLayout;